const _ = require('lodash');

module.exports = function(db) {
  const collection = db.collection('statistics-arena-rooms');
  const indexes = [
    { key: { season_id: 1 }, name: 'season_id_1' },
    { key: { arena_room_id: 1 }, name: 'arena_room_id_1' },
    { key: { date: 1 }, name: 'date_1' },
  ];

  collection.createIndexes(indexes);

  return {
    name: 'statisticsArenaRooms',
    updateArenaRoom: function(selector, update, options) {
      return collection.updateOne(selector, update, {
        upsert: true,
        ...options,
      });
    },

    findSeasonRooms: function(date) {
      const projection = {
        projection: { arena_room_id: 1, season_id: 1 },
      };
      return collection.find({ date }, projection).toArray();
    },

    countSeasonBalance: function(season_id) {
      return collection
        .aggregate([
          { $match: { season_id } },
          {
            $group: {
              _id: '$season_id',
              total_room_cost_gold: { $sum: '$room_cost_gold' },
              total_user_win_gold: { $sum: '$user_win_gold' },
              total_user_lose_gold: { $sum: '$user_lose_gold' },
              total_ai_win_gold: { $sum: '$ai_win_gold' },
              total_ai_lose_gold: { $sum: '$ai_lose_gold' },
            },
          },
        ])
        .toArray();
    },
  };
};
